using System;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using Sharpmark.PerfectLife.ColorfulPhotos.Framework.Picture;

namespace Sharpmark.PerfectLife.ColorfulPhotos.Framework.Utilities.ImageToText
{
	public class TextString : TextBase
	{
		public TextString(int charWidth, int charHeight, char bgchar, char ftchar, string cn, Font font)
			: base(charWidth, charHeight)
		{
			BackgroundChar = bgchar;
			FrontChar = ftchar;
			Content = cn;
			Font = font;
		}

		protected char _backgroundChar;
		protected char _frontChar;
		protected string _content;
		protected Font _font;

		public char BackgroundChar
		{
			get { return _backgroundChar; }
			set { _backgroundChar = value; }
		}

		public Font Font
		{
			get { return _font; }
			set { _font = value; }
		}

		public char FrontChar
		{
			get { return _frontChar; }
			set { _frontChar = value; }
		}

		public string Content
		{
			get { return _content; }
			set { _content = value; }
		}

		public override string GenerateText()
		{
			//TODO: ASCII和汉字表示不同，长宽比要调节
			StringBuilder sb = new StringBuilder();
			PixelFormat format = PixelFormat.Format32bppArgb;

			// 获取字体大小
			SizeF size = Graphics.FromImage(
				new Bitmap(_charsWidth, _charsHeight, format)).MeasureString(Content, Font);

			// 根据字体创建图形
			int sw = Int32.Parse(Math.Round(size.Width).ToString());
			int sh = Int32.Parse(Math.Round(size.Height).ToString());
			Bitmap bitmapOrg = new Bitmap(sw, sh, format);
			Graphics g = Graphics.FromImage(bitmapOrg);
			
			// 描绘图形
			g.FillRectangle(Brushes.White, 0, 0, sw, sh);
			g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
			g.DrawString(Content, _font, Brushes.Black, 0, 0);

			// 缩放到指定大小
			bitmapOrg = (Bitmap)bitmapOrg.GetThumbnailImage(_charsWidth, _charsHeight, null, IntPtr.Zero);

			for (int h = 0; h < _charsHeight; h++)
			{
				for (int w = 0; w < _charsWidth; w++)
				{
					System.Drawing.Color cc = bitmapOrg.GetPixel(w, h);
					if (cc.ToArgb() == Color.White.ToArgb())
						sb.Append(_backgroundChar);
					else
						sb.Append(_frontChar);
				}

				sb.Append(System.Environment.NewLine);
			}

			return sb.ToString();
		}

		private void GetImageFromFont()	//test
		{
			//SizeF size = g.MeasureString("a", new Font("Courier New", 24));
			//return new Photo(
			//    Int32.Parse(Math.Round(size.Width).ToString()),
			//    Int32.Parse(Math.Round(size.Height).ToString()), g);	
		}
	}
}
